package com.realgodo.site.service.application;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.application.vote.Vote;
import com.realgodo.site.entity.application.vote.VoteItem;
import com.realgodo.site.entity.application.vote.VoteRecord;
import com.realgodo.site.entity.space.Space;

/**
 * @author bijiqiang E-mail: bijiqiang@gmail.com
 * @version 创建时间：2009-12-13下午04:35:45
 * @since jdk1.5
 * @version 0.1
 */
@Service("voteManager")
@Transactional
public class VoteManager extends DefaultEntityManager<Vote, Long> {
	@Autowired
	protected SessionFactory sessionFactory;
	@Autowired
	private VoteItemManager voteItemManager;
	@Autowired
	private VoteRecordManager voteRecordManager;

	/**
	 * 添加一个投票
	 * 
	 * @param vote
	 * @param items
	 */
	public void addVote(Vote vote, List<VoteItem> items) {

		Session session = sessionFactory.getCurrentSession();
		if (null != vote.getSpace()) {
			vote.setClasz(Vote.class);
			vote = (Vote) this.entityDao.saveMerge(vote);
		}
		for (VoteItem item : items) {
			if (null == item.getTitle() || "".equals(item.getTitle())) {
				continue;
			}
			item.setVote(vote);
			session.save(item);
		}
	}

	/**
	 * 获得我发起的投票
	 * 
	 * @param space
	 * @param maxResult
	 * @return
	 */
	public Page<Vote> getMyVotes(Page<Vote> list, Space space) {

		Session session = this.sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Vote.class);

		criteria.add(Restrictions.eq("space.id", space.getId()));
		criteria.addOrder(Order.desc("pubTime"));

		return super.getEntityDao().findByCriteria(list, criteria);
	}

	/**
	 * 获取我的好友的投票
	 * 
	 * @param list
	 * @param space
	 * @return
	 */
	public Page<Vote> getFriendsVotes(Page<Vote> list, Space space) {
		return null;
	}

	/**
	 * 根据投票主键投票项
	 * 
	 * @param voteId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<VoteItem> getVoteItems(Long voteId) {
		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery(" select o from VoteItem o where o.vote.id = ?");
		hql.setParameter(0, voteId);
		return hql.list();
	}

	/**
	 * 投票
	 * 
	 * @param vote
	 * @param itemIds
	 * @param space
	 * @return
	 */
	public boolean vote(Vote vote, Long[] itemIds, Space space) {
		if (hasVoteRecord(space, vote)) {
			return false;
		}
		VoteRecord record = null;
		VoteItem item = null;
		for (Long itemId : itemIds) {

			vote.setTotalCount(vote.getTotalCount() + 1L);
			vote = (Vote) this.saveMerge(vote);
			item = this.voteItemManager.get(itemId);
			item.setVoteCount(item.getVoteCount() + 1L);
			this.voteItemManager.saveMerge(item);

			record = new VoteRecord();
			record.setVoteItem(item);
			record.setVoter(space);
			record.setVoteTime(new Date());
			this.voteRecordManager.saveMerge(record);
		}
		return true;
	}

	/**
	 * 用户是否投过票
	 * 
	 * @param space
	 * @param vote
	 * @return
	 */
	public boolean hasVoteRecord(Space space, Vote vote) {
		Long count = 0L;
		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery(" select count(o) from VoteRecord o where o.voteItem.vote.id = ? and o.voter.id= ?");
		hql.setParameter(0, vote.getId());
		hql.setParameter(1, space.getId());
		if (null != hql.list()) {
			count = (Long) hql.list().get(0);
		}
		return count > 0;
	}

	/**
	 * 获取我参与的投票
	 * @param list
	 * @param space
	 * @return
	 */
	public Page<Vote> getMyJoinVotes(Page<Vote> list, Space space) {
		List<Vote> votes = new ArrayList<Vote>();
		Page<VoteRecord> pages = new Page<VoteRecord>();
		pages.setAutoCount(list.isAutoCount());
		pages.setPageNo(list.getPageNo());
		pages.setPageSize(list.getPageSize());
		pages.setTotalCount(list.getTotalCount());
		 Page<VoteRecord> records = this.voteRecordManager.getMyJoinVoteRecords(pages, space);
		 for(VoteRecord record :records.getResult()){
			 votes.add(record.getVoteItem().getVote());
		 }
		 list.setResult(votes);
		 return list;
	}
	
	/**
	 * 获取热门投票
	 * @param list
	 * @param space
	 * @return
	 */
	public Page<Vote> getHotVotes(Page<Vote> list) {

		Session session = this.sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Vote.class);
		criteria.addOrder(Order.desc("totalCount"));

		return super.getEntityDao().findByCriteria(list, criteria);
	}
}
